package com.fenghongzhang.camera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Color;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MicrophoneDirection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.alibaba.android.arouter.facade.annotation.Route;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.util.List;

import io.reactivex.functions.Consumer;

@Route(path = "/camera/mainActivity")
public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    private SurfaceView surfaceView;
    private Button start;
    private Button stop;
    private Button play;

    String absolutePath;
    private MediaRecorder mRecorder;
    private SurfaceHolder mSurfaceHolder;
    private Camera camera;
    boolean mIsPlay;

    String path;
    private MediaPlayer mediaPlayer;
    private RxPermissions rxPermissions = new RxPermissions(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        rxPermissions.request(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO)
                .subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if(!aBoolean){
                    Toast.makeText(CameraActivity.this, "必须都要同意哦", Toast.LENGTH_SHORT).show();
                }
            }
        });

        View decor = getWindow().getDecorView();
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);


        surfaceView = (SurfaceView) findViewById(R.id.surface_view);
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        play = (Button) findViewById(R.id.play);


        mSurfaceHolder = surfaceView.getHolder();
        mSurfaceHolder.addCallback(this);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mIsPlay) {
                    if (mediaPlayer != null) {
                        mIsPlay = false;
                        mediaPlayer.stop();
                        mediaPlayer.reset();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                }

                if (mRecorder == null) {
                    mRecorder = new MediaRecorder();
                }

                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
//                Camera.Parameters parameters = camera.getParameters();
//                List<Integer> supportedPreviewFrameRates = parameters.getSupportedPreviewFrameRates();
//                for (int i = 0; i < supportedPreviewFrameRates.size(); i++) {
//                    Integer integer = supportedPreviewFrameRates.get(i);
//                }

//                    Camera.Parameters parameters = camera.getParameters();
//                    List<Camera.Size> supportedVideoSizes = parameters.getSupportedVideoSizes();
//                    for (int i = 0; i < supportedVideoSizes.size(); i++) {
//                        Camera.Size size = supportedVideoSizes.get(i);
//                        Log.i(TAG, "onClick: "+"宽"+size.width+"高"+size.height);
//
//                    }
                if (camera != null) {
                    camera.setDisplayOrientation(90);
                    camera.unlock();
                    mRecorder.setCamera(camera);
                }

                try {
                    // 这两项需要放在setOutputFormat之前
                    mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
                    mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

                    // Set output file format
                    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

                    // 这两项需要放在setOutputFormat之后
                    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);

                    //camera.getSupportedVideoSizes（）
                    mRecorder.setVideoSize(640, 480);
                    mRecorder.setVideoFrameRate(30);
                    mRecorder.setVideoEncodingBitRate(3 * 1024 * 1024);
                    mRecorder.setOrientationHint(90);
                    //设置记录会话的最大持续时间（毫秒）
                    mRecorder.setMaxDuration(30 * 1000);
                    mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

                    path = getSDPath();
                    if (path != null) {
                        File dir = new File(path + "/recordtest");
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        path = dir + "/" + System.currentTimeMillis() + ".mp4";
                        mRecorder.setOutputFile(path);
                        mRecorder.prepare();
                        mRecorder.start();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mRecorder.stop();
                    mRecorder.reset();
                    mRecorder.release();
                    mRecorder = null;
                    if (camera != null) {
                        camera.release();
                        camera = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });


        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mIsPlay = true;

                if (mediaPlayer == null) {
                    mediaPlayer = new MediaPlayer();
                }
                mediaPlayer.reset();
                Uri uri = Uri.parse(path);
                mediaPlayer = MediaPlayer.create(CameraActivity.this, uri);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDisplay(mSurfaceHolder);
                try{
                    mediaPlayer.prepare();
                }catch (Exception e){
                    e.printStackTrace();
                }
                mediaPlayer.start();

            }
        });

    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            return sdDir.toString();
        }

        return null;
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        mSurfaceHolder = holder;
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        mSurfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        surfaceView = null;
        mSurfaceHolder = null;
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
        if (camera != null) {
            camera.release();
            camera = null;
        }
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
